import React, { Component } from 'react'

export default class Menu extends Component {
    constructor () {
        super();
        this.state = {
            openMenu: 0,
            menu: [
                { id: 1, menu: '菜单1', pid: 0 },
                { id: 2, menu: '菜单2', pid: 0 },
                { id: 3, menu: '菜单1-1', pid: 1 },
                { id: 4, menu: '菜单1-2', pid: 1 },
                { id: 8, menu: '菜单1-3', pid: 1 },
                { id: 5, menu: '菜单2-1', pid: 2 },
                { id: 6, menu: '菜单2-2', pid: 2 },
                { id: 7, menu: '菜单2-3', pid: 2 },
            ]
        }
    }
    changOpen(pid) {
        if (pid !== this.state.openMenu) {
            this.setState({
                openMenu: pid * 1
            })
        } else {
            this.setState({
                openMenu: 0
            })
        }
    }
    openMnue(item) {
        let html = ''
        if (item.id === this.state.openMenu) {
            html = this.state.menu.filter(obj => obj.pid === item.id).map(obj => <div style={{ padding: '5px 10px' }} key={obj.id}>{obj.menu}</div>)
        }
        return html
    }
    render() {
        return (
            <div>
                <div className='menu2'>
                    {this.state.menu.filter(item => item.pid === 0).map(item =>
                        <div style={{ flex: '1' }} key={item.id}>
                            <p onClick={() => { this.changOpen(item.id) }} >{item.menu}</p>
                            {this.openMnue(item)}
                        </div>
                    )}
                </div>
            </div>
        )
    }
}
